/**
 * Created by PanJiaChen on 16/11/18.
 */

import CryptoJS from 'crypto-js/crypto-js'
import { calendar } from './calendar.js'
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    if (option === 'false') {
      return (
        d.getMonth() +
                1 +
                '月' +
                d.getDate() +
                '日'
      )
    } else {
      return parseTime(time, option)
    }
  } else {
    return (
      d.getMonth() +
            1 +
            '月' +
            d.getDate() +
            '日' +
            d.getHours() +
            '时' +
            d.getMinutes() +
            '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
        decodeURIComponent(search)
          .replace(/"/g, '\\"')
          .replace(/&/g, '","')
          .replace(/=/g, '":"')
          .replace(/\+/g, ' ') +
        '"}'
  )
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
            classString.substr(0, nameIndex) +
            classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

/**
 *加密处理
 */
export const encryption = (params) => {
  let {
    // eslint-disable-next-line prefer-const
    data,
    // eslint-disable-next-line prefer-const
    type,
    // eslint-disable-next-line prefer-const
    param,
    key
  } = params
  const result = JSON.parse(JSON.stringify(data))
  if (type === 'Base64') {
    param.forEach(ele => {
      result[ele] = btoa(result[ele])
    })
  } else {
    param.forEach(ele => {
      var data = result[ele]
      key = CryptoJS.enc.Latin1.parse(key)
      var iv = key
      // 加密
      var encrypted = CryptoJS.AES.encrypt(
        data,
        key, {
          iv: iv,
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.ZeroPadding
        })
      result[ele] = encrypted.toString()
    })
  }
  return result
}

// 表单序列化
export const serialize = data => {
  const list = []
  Object.keys(data).forEach(ele => {
    list.push(`${ele}=${data[ele]}`)
  })
  return list.join('&')
}

// fromData
export function toFormData(data) {
  const tableRequestParam = new FormData()
  tableRequestParam.append('page', data.page)
  tableRequestParam.append('rows', data.rows)
  tableRequestParam.append('sort', data.sort)
  tableRequestParam.append('order', data.order)
  tableRequestParam.append('pageFlag', data.pageFlag)
  tableRequestParam.append('onlyCountFlag', data.onlyCountFlag)
  tableRequestParam.append('filtersRaw', JSON.stringify(data.filtersRaw))
  return tableRequestParam
}

/**
 * JSON对象转formData
 * @param {Object} JSON对象
  */
export function json2FormData(params) {
  const formData = new FormData()
  Object.keys(params).forEach((key) => {
    formData.append(key, params[key])
  })
  return formData
}

/**
 * 生成随机len位数字
 */
export const randomLenNum = (len, date) => {
  let random = ''
  random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len || 4)
  if (date) random = random + Date.now()
  return random
}

/**
 * 替换内容里面的url为超链接
 */
export function replaceUrlToLink(content) {
  const rs = /(http:\/\/)?([A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*)/g
  content = content.replace(rs, function(a, b, c) { return '<a class="link-style" href="http://' + c + '">' + a + '</a>' })
  return content
}

/**
 * 判断是否为IE
 */
export function detectIE() {
  var ua = window.navigator.userAgent
  var msie = ua.indexOf('MSIE ')
  if (msie > 0) {
    // IE 10 or older => return version number
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10)
  }

  var trident = ua.indexOf('Trident/')
  if (trident > 0) {
    // IE 11 => return version number
    var rv = ua.indexOf('rv:')
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10)
  }

  var edge = ua.indexOf('Edge/')
  if (edge > 0) {
    // Edge (IE 12+) => return version number
    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10)
  }

  // other browser
  return false
}

//
const toString = Object.prototype.toString
/** 判断类型
 * @param {any} inp
 * @param {string} type
 * @returns {string}
 */
export function isType(inp, type) {
  return toString.call(inp).substr(8).replace(/\]$/, '').toLowerCase() === type.toLowerCase()
}

/** deep copy
 * @param {Array|Object} source
 * @returns {Array|Object}
 */
export function deepCopy(source) {
  let target
  if (isType(source, 'Array')) {
    target = []
    for (const e of source) {
      target.push(deepCopy(e))
    }
  } else if (isType(source, 'Object')) {
    target = {}
    for (const key of Object.keys(source)) {
      target[key] = deepCopy(source[key])
    }
  } else {
    return source
  }
  return target
}

/** hasValue
 * @param {any} v
 * @returns {boolean}
 */
export function hasValue(v) {
  return v !== undefined && v !== null
}
/** notEmpty
 * @param {any} v
 * @returns {boolean}
 */
export function notEmpty(v) {
  return hasValue(v) && v !== ''
}
/** 根据属性链获取属性值
 * @param {object | array} source
 * @param {string} chain
 * @param {any} defValue 默认值
 * @returns {any}
 */
export function getValueByChain(source, chain, defValue = '') {
  let v = source
  try {
    const props = chain.split('.')
    for (const prop of props) {
      v = v[prop]
      if (v === undefined || v === null) {
        return defValue
      }
    }
  } catch (error) {
    console.log(error)
  }
  if (v === undefined) {
    v = defValue
  }
  return v
}
/** 通过a标签下载文件
 * @param {string} href
 * @param {string} fileName
 */
export function downFileByA(href, fileName) {
  if (!hasValue(fileName)) {
    fileName = new Date().getTime().toString() + href.split('/').pop()
  }
  const a = document.createElement('a')
  a.href = href
  a.download = fileName
  a.click()
}
// 将date根据type转换为年-月-日(农历/公历)
export function transShowDate(date, type) {
  if (!date) {
    return ''
  }
  const tdate = new Date(date)
  const y = tdate.getFullYear()
  const m = tdate.getMonth() + 1
  const d = tdate.getDate()
  var thisDate = calendar.solar2lunar(y, m, d)
  thisDate.cMonth < 10 ? thisDate.cMonth = `0${thisDate.cMonth}` : ''
  thisDate.cDay < 10 ? thisDate.cDay = `0${thisDate.cDay}` : ''
  thisDate.lMonth < 10 ? thisDate.lMonth = `0${thisDate.lMonth}` : ''
  thisDate.lDay < 10 ? thisDate.lDay = `0${thisDate.lDay}` : ''
  if (type === 'solar') {
    return (thisDate.cYear + '-' + thisDate.cMonth + '-' + thisDate.cDay + '(公历)')
  } else {
    return (thisDate.lYear + '-' + thisDate.lMonth + '-' + thisDate.lDay + '(农历)')
  }
}
// 根据农历公历转str
export function date2Str(date, type) {
  if (!date) {
    return ''
  }
  const tdate = new Date(date)
  const y = tdate.getFullYear()
  const m = tdate.getMonth() + 1
  const d = tdate.getDate()
  var thisDate = calendar.solar2lunar(y, m, d)
  thisDate.cMonth < 10 ? thisDate.cMonth = `0${thisDate.cMonth}` : ''
  thisDate.cDay < 10 ? thisDate.cDay = `0${thisDate.cDay}` : ''
  thisDate.lMonth < 10 ? thisDate.lMonth = `0${thisDate.lMonth}` : ''
  thisDate.lDay < 10 ? thisDate.lDay = `0${thisDate.lDay}` : ''
  if (type === 'solar') {
    return (thisDate.cYear + '-' + thisDate.cMonth + '-' + thisDate.cDay)
  } else {
    return (thisDate.lYear + '-' + thisDate.lMonth + '-' + thisDate.lDay)
  }
}
// 农历、公历互转
export function ls(dateStr, type) {
  if (dateStr === '' || dateStr === undefined) {
    return ''
  }
  if (type === 'solar') {
    const date = new Date(dateStr)
    return date
  }
  let t = ''
  const date = dateStr.split('-')
  const lm = calendar.leapMonth(date[0])

  if (lm !== 0 && lm.toString() === date[1]) {
    t = calendar.lunar2solar(date[0], date[1], date[2], true)
  } else {
    t = calendar.lunar2solar(date[0], date[1], date[2])
  }
  if (t < 0 || t === '') {
    return ''
  }
  return new Date(t.cYear, t.cMonth - 1, t.cDay)
}
/** 返回filtersRaw的项
 * @param {string} property 属性名称
 * @param {string} value 值
 * @param {string} operator 参考sql =,<>,<,>,<=,>=,in,like等
 * @param {string} id 默认为空字符串
 */
export function filtersRaw(property, value, operator, id = '') {
  if (isType(value, 'Date')) {
    value = parseTime(value)
  }
  return {
    id: id || Math.floor(Math.random() * 0xffffffffff).toString(16),
    property,
    operator,
    value: typeof value === 'object' ? JSON.stringify(value) : value
  }
}
/** 23：59：59
 * @param {object} date 属性名称串
 */
export function date24(date) {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1, 0, 0, 0)
}
/** 获取当天时间24小时 */
export function currDatePeriod() {
  const d = new Date()
  return [new Date(d.getFullYear(), d.getMonth(), d.getDate()), new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59)]
}
/** 返回分页参数
 * @param {object} body 属性名称串
 */
export function pageRequsetBody(body = {}) {
  const formData = new FormData()
  for (const key of Object.keys(body)) {
    let v = body[key]
    if (isType(v, 'Array') || isType(v, 'Object')) {
      v = JSON.stringify(v)
    }
    formData.append(key, v)
  }
  return formData
}
/**
 * 对象转查询参数
 * @param {object} data
 */
export function objToQuery(data) {
  const query = []
  for (const key of Object.keys(data)) {
    let v = data[key]
    if (typeof v === 'object') {
      v = JSON.stringify(v)
    }
    query.push(`${key}=${v}`)
  }
  return query.join('&')
}
/** 下载文件
 * @params {binary} data
*/
export function downFileByStream(data, fileName) {
  // const fileData = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  downFileByA(window.URL.createObjectURL(data), fileName)
}
/** 数字字符串转换 */
export function numToString(v) {
  if (/^\d+$/.test(v)) {
    return v.toString()
  }
  return v
}
export function strToNumber(v) {
  if (/^\d+$/.test(v)) {
    return parseInt(v)
  } else if (/^\d+\.\d*$/.test(v)) {
    return parseFloat(v)
  }
  return v
}
/** 日期增加一天 */
export function addOneDay(date) {
  date = new Date(date)
  date = date.getTime() + (1000 * 3600 * 24)
  date = new Date(date)
  const y = date.getFullYear()
  const m = date.getMonth() + 1
  const d = date.getDate()
  return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d)
}

// 验证非空数据
export function isEmpty(data) {
  if (isType(data, 'Array') && data.length <= 0) {
    return true
  } else if ((isType(data, 'String') && data.length <= 0) || data === '') {
    return true
  } else if (data === null || data === undefined) {
    return true
  } else if (isType(data, 'Object') && Object.keys(data).length <= 0) {
    return true
  }
  return false
}
// 检查日期跨度
export function checkRange(durtion = 92) {
  return function(v) {
    // 不超过三个月
    const t1 = new Date(v[0]).getTime()
    const t2 = new Date(v[1]).getTime()
    if (t2 - t1 > durtion * 24 * 60 * 60 * 1000) {
      return false
    }
    return true
  }
}
